package com.gem.day16;

import java.io.*;
import java.net.Socket;
import java.util.List;

/**服务线程,实现群聊*/
public class TalkThread extends Thread {
	//所有的客户端对象
	private List<Socket> clients;
	//自己的客户端对象
	private Socket self;

	public TalkThread(List<Socket> clients, Socket self) {
		this.clients = clients;
		this.self = self;
	}

	@Override
	public void run() {
		//获取输入/输出流
		//桥接器转换
		try (BufferedReader br = new BufferedReader(new InputStreamReader(self.getInputStream()));) {
			//读取数据
			String line = null;
			while ((line = br.readLine()) != null) {
				//客户端退出功能
				if (line.equalsIgnoreCase("exit")) {
					System.out.println(self.getInetAddress().getHostAddress() + "离开了.");
					//把信息发送给所有的客户端
					String msg = "我下线了~";
					sendMsg(msg);
					//移除客户端集合中的下线客户
					clients.remove(self);
					break;
				}
				sendMsg(line);
			}
		} catch (Exception e) {
			//异常情况
			System.out.println(self.getInetAddress().getHostAddress() + "离开了.");
			clients.remove(self);
		} finally {
			try {
				self.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发送信息的方法
	 * @throws IOException 
	 */
	private void sendMsg(String line) throws IOException {
		PrintWriter pw = null;
		String ip = self.getInetAddress().getHostAddress();
		line = "[" + ip + "]说: " + line;
		//读取到数据广播中每一个客户端,除了自己以外
		for (Socket socket : clients) {
			if (socket != self) {
				pw = new PrintWriter(socket.getOutputStream());
				pw.println(line);
				//刷新缓存
				pw.flush();
			}
		}
	}
}
